import { join } from "node:path";
import AutoLoad, { AutoloadPluginOptions } from "@fastify/autoload";
import { FastifyPluginAsync, FastifyServerOptions } from "fastify";
// 导入路由文件
// import rootRoutes from './routes/root'
// 导入其他路由文件
// import roomsRoutes from './routes/rooms/index'
// 导入 v1 API 路由
// import v1RoomsRoutes from './routes/v1/rooms/index'
import v1CreateRoomRoutes from "./routes/v1/rooms/create-room";
import v1DeleteRoomRoutes from "./routes/v1/rooms/update-room";
import v1GetRoomRoutes from "./routes/v1/rooms/get-rooms";
import captchaRoutes from "./routes/v1/captcha/index";

import v2CreateOrderRoutes from "./routes/v2/orders/create-order";

import v2GetInvitationsRoutes from "./routes/v2/invitations/get-invitations";

export interface AppOptions
  extends FastifyServerOptions,
    Partial<AutoloadPluginOptions> {}
// Pass --options via CLI arguments in command to enable these options.
const options: AppOptions = {};

const app: FastifyPluginAsync<AppOptions> = async (
  fastify,
  opts,
): Promise<void> => {
  // 全局初始化 captchaStore
  if (!fastify.hasDecorator("captchaStore")) {
    fastify.decorate("captchaStore", new Map());

    // 设置清理过期验证码的定时任务
    const interval = setInterval(
      () => {
        const now = Date.now();
        for (const [id, data] of fastify.captchaStore.entries()) {
          if (data.expireAt < now) {
            fastify.captchaStore.delete(id);
          }
        }
      },
      5 * 60 * 1000,
    ); // 每5分钟清理一次

    fastify.addHook("onClose", () => clearInterval(interval));
  }

  // Do not touch the following lines

  // This loads all plugins defined in plugins
  // those should be support plugins that are reused
  // through your application
  // eslint-disable-next-line no-void
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "plugins"),
    options: opts,
  });
  //
  // // This loads all plugins defined in routes
  // // define your routes in one of these
  // // eslint-disable-next-line no-void
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "routes"),
    options: opts,
  });
  //
  // // 注册v1路由
  // void fastify.register(AutoLoad, {
  //   dir: join(__dirname, 'routes/v1'),
  //   options: { prefix: '/api/v1' }, // 一级前缀
  //   routeParams: true
  // });
  // 房间路由
  // fastify.register(roomsRoutes, { prefix: '/rooms' })

  // v1 API 路由
  // fastify.register(v1RoomsRoutes, { prefix: '/api/v1/rooms' })
  fastify.register(v1CreateRoomRoutes, { prefix: "/api/v1/rooms" });
  fastify.register(v1DeleteRoomRoutes, { prefix: "/api/v1/rooms" });
  fastify.register(v1GetRoomRoutes, { prefix: "/api/v1/rooms" });
  fastify.register(captchaRoutes, { prefix: "/api/v1/captcha" });

  fastify.register(v2CreateOrderRoutes, { prefix: "/api/v2/orders" });
  fastify.register(v2GetInvitationsRoutes, { prefix: "/api/v2/invitations" });
};

export default app;
export { app, options };
